package com.epfresh.supplier.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.dialog.TimePickerDialog;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.DateUtil;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.api.widget.PhotoAddGroup;
import com.epfresh.api.widget.SlideSwitch;
import com.epfresh.api.widget.TagCommView;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.delegate.UploadProductDelegate;
import com.epfresh.supplier.entity.Category;
import com.epfresh.supplier.entity.Images;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.ProductAddEntity;
import com.epfresh.supplier.entity.Promotion;
import com.epfresh.supplier.entity.PurchaseInfo;
import com.epfresh.supplier.entity.StoreInfo;
import com.epfresh.supplier.entity.TagEntity;
import com.epfresh.supplier.entity.TagPackage;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ProductAddActivity extends BaseActivity {
    //是否线上销售
    private View vOrder;
    private SlideSwitch ssOrder;
    //预计送达时间
    private CommonInputItem ciInDate;
    //预计截止时间
    private CommonInputItem ciDateline;
    //分类
    private CommonInputItem ciProductClassify;
    //品名
    private CommonInputItem ciProductSpecName;
    //包装
    private CommonInputItem ciProductPackage;
    //产地
    private CommonInputItem ciProductArea;
    //商品标题
    private CommonInputItem ciProductTitle;
    //商品规格
    private CommonInputItem ciProductSpec;
    //商品价格
    private CommonInputItem ciProductPrice;
    //商品起定量
    private CommonInputItem ciProductMoq;
    //商品标签
    private CommonInputItem ciProductTag;
    //促销活动
    private CommonInputItem ciProductActivity;
    //秒杀
    private CommonInputItem ciProductSecKill;
    //商品价格及起定量图标
    private ImageView ivPriceMoq;
    //进货信息
    private CommonInputItem ciProductStock;
    //库存输入框
    private EditText edInventory;
    //库存单位
    private TextView tvInventory;
    //详情
    private EditText edProductDescribe;

    private TagCommView tvTag;
    private View rlPackageTips;

    private TextView tvBtn;
    private TextView tvDraft;
    private TextView tvDelete;
    private TextView tvInventoryTitle;
    private TextView tvPackageUnit;
    private TextView tvPackageSize;
    private View rlPackage;
    private boolean isCashProduct;
    private boolean isAddProduct;
    private String type;
    private String productId;
    private ProductAddEntity productAddEntity = new ProductAddEntity();
    private PhotoCore photoCore;
    private PhotoCore photoCoreDetail;
    private PhotoAddGroup pag;
    private UploadProductDelegate upd;
    private boolean isTextSetProgrammatically = true;
    private EditText edTitle;
    private boolean isModifyJinHuo = false;//判断是否修改了进货信息

    private boolean isFirst;
    //上下架，1上架列表，2下架列表,3草稿,4审核
    private int listType;

    //1,分类,显示品名
    boolean isCategoryType;
    String orderId;
    boolean isInventory;

    private String pinlei;
    private boolean moml;

    private boolean isModify = false;
    private String saveUnit;
    private double saveIncr;
    private boolean isModify1;
    private RelativeLayout rlOnlineSale;

    TextWatcher textListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            isTextSetProgrammatically = false;
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_add);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);

        if (savedInstanceState != null) {
            getIntent().putExtra(Constant.TYPE, savedInstanceState.getString(Constant.TYPE));
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("is_first", savedInstanceState.getBoolean("is_first"));
            getIntent().putExtra("isCategoryType", savedInstanceState.getBoolean("isCategoryType"));
            getIntent().putExtra("listType", savedInstanceState.getInt("listType"));
            getIntent().putExtra("dataProduct", savedInstanceState.getString("dataProduct"));
            getIntent().putExtra("orderId", savedInstanceState.getString("orderId"));
            String dataProduct = getIntent().getStringExtra("dataProduct");
            if (dataProduct != null && !"".equals(dataProduct)) {
                DataManager.getInstance().setProductAddEntity(new Gson().fromJson(dataProduct, ProductAddEntity.class));
            }
        }

        pinlei = getIntent().getStringExtra("pinlei");
        moml = getIntent().getBooleanExtra("moml", true);

        isInventory = getIntent().getBooleanExtra("is_inventory", false);
        orderId = getIntent().getStringExtra("orderId");
        isCategoryType = getIntent().getBooleanExtra("isCategoryType", false);
        //上下架，1上架列表，2下架列表,0草稿,4审核
        listType = getIntent().getIntExtra("listType", -1);
        type = getIntent().getStringExtra(Constant.TYPE);
        productId = getIntent().getStringExtra("productId");
        isAddProduct = getIntent().getBooleanExtra("is_first", false);
        if (type != null && "1".equals(type)) {
            //现售
            isCashProduct = true;
            toolbarTitle.setText(R.string.cash_product);
            productAddEntity.setType("1");
        } else if (type != null && "2".equals(type)) {
            //预售
            isCashProduct = false;
            toolbarTitle.setText(R.string.pre_product);
            productAddEntity.setType("2");
        } else {
            finish();
        }
        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (hasProductId()) {
            isCategoryType = intent.getBooleanExtra("isCategoryType", false);

            boolean isClassifySame = intent.getBooleanExtra("is_classify_same", false);
            boolean isSame = intent.getBooleanExtra("is_same", false);

            Log.e("isCategoryType", "isClassifySame:" + isClassifySame);
            productAddEntity = DataManager.getInstance().getProductAddEntity();
            if (productAddEntity != null) {
                productAddEntity.setTitle(getRecommendTitle());
            }
            initProduct();
            if (!isClassifySame) {
                ciProductClassify.setContentText("");
                if (BaseApplication.getInstance().getMerchant().isCategoryLevelOne()) {
                    productAddEntity.setStoreTopCategoryId(null);
                    productAddEntity.setStoreTopCategoryName(null);
                } else {
                    productAddEntity.setStoreCategoryId(null);
                    productAddEntity.setStoreCategoryName(null);
                }
            }
            if (!isSame) {
                ciProductSpecName.setContentText("");
            }
        }
    }

    private void initView() {
        if (productAddEntity == null) {
            finish();
            return;
        }
        rightbtn.setText(getString(R.string.help));
        rightbtn.setTextColor(0xff898989);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setOnClickListener(this);
        rlOnlineSale = findViewById(R.id.rl_online_sale);
        ssOrder = (SlideSwitch) findViewById(R.id.ss_receive);
        ssOrder.setOnClickListener(this);
        vOrder = findViewById(R.id.v_receive);
        vOrder.setOnClickListener(this);
        ssOrder.setSlideable(false);

        rlPackage = findViewById(R.id.rl_package);
        tvPackageSize = (TextView) findViewById(R.id.tv_package_size);
        tvPackageUnit = (TextView) findViewById(R.id.tv_package);

        ciInDate = (CommonInputItem) findViewById(R.id.ci_in_date);
        ciDateline = (CommonInputItem) findViewById(R.id.ci_dateline);

        ciProductClassify = (CommonInputItem) findViewById(R.id.ci_product_classify);
        ciProductPackage = (CommonInputItem) findViewById(R.id.ci_product_package);
        ciProductArea = (CommonInputItem) findViewById(R.id.ci_product_area);
        ciProductSpecName = (CommonInputItem) findViewById(R.id.ci_product_spec_name);

        ciProductTitle = (CommonInputItem) findViewById(R.id.ci_product_title);
        ciProductSpec = (CommonInputItem) findViewById(R.id.ci_product_spec);
        ciProductPrice = (CommonInputItem) findViewById(R.id.ci_product_price);
        ciProductMoq = (CommonInputItem) findViewById(R.id.ci_product_moq);
        ciProductStock = (CommonInputItem) findViewById(R.id.ci_product_stock);
        ciProductTag = (CommonInputItem) findViewById(R.id.ci_product_tag);
        ciProductActivity = (CommonInputItem) findViewById(R.id.ci_product_activity);
        ciProductSecKill = (CommonInputItem) findViewById(R.id.ci_product_seckill);

        ivPriceMoq = (ImageView) findViewById(R.id.iv_product_price_flag);

        edInventory = (EditText) findViewById(R.id.ed_inventory);
        edProductDescribe = (EditText) findViewById(R.id.ed_product_describe);
        tvInventory = (TextView) findViewById(R.id.tv_inventory_unit);
        tvInventoryTitle = (TextView) findViewById(R.id.tv_inventory_title);
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 9999999;
        edInventory.setFilters(new InputFilter[]{cashierInputFilter});
        ciProductSpec.setOnClickListener(this);

        ciProductPrice.setOnClickListener(this);
        ciProductMoq.setOnClickListener(this);
        ivPriceMoq.setOnClickListener(this);

        ciProductStock.setOnClickListener(this);
        ciProductTag.setOnClickListener(this);
        ciProductActivity.setOnClickListener(this);
        ciProductSecKill.setOnClickListener(this);
        ciProductClassify.setOnClickListener(this);
        ciProductPackage.setOnClickListener(this);
        ciProductArea.setOnClickListener(this);
        ciProductSpecName.setOnClickListener(this);
        ciInDate.setOnClickListener(this);
        ciDateline.setOnClickListener(this);
        tvBtn = (TextView) findViewById(R.id.tv_btn);
        tvDelete = (TextView) findViewById(R.id.tv_delete);
        tvDraft = (TextView) findViewById(R.id.tv_draft);
        tvBtn.setOnClickListener(this);
        tvDraft.setOnClickListener(this);
        tvDelete.setOnClickListener(this);
        //上下架，1上架列表，2下架列表,0,草稿,4审核
        if (listType == 1) {
//            tvDelete.setText("删除");
            tvDraft.setVisibility(View.GONE);
//            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tvDelete.getLayoutParams();
//            lp.weight = 1;
//            tvDelete.setLayoutParams(lp);
            tvDelete.setVisibility(View.GONE);
            LinearLayout.LayoutParams lp0 = (LinearLayout.LayoutParams) tvBtn.getLayoutParams();
            lp0.weight = 1;
            tvBtn.setLayoutParams(lp0);
        } else if (listType == 2) {
            tvDelete.setText("删除");
            tvDraft.setText("保存");
        } else if (listType == 0) {
            tvDelete.setText("删除");
            tvDraft.setText("保存");
        } else if (listType == 3) {
            tvDelete.setText("放弃");
            tvDraft.setText("保存为草稿");
        }
        pag = (PhotoAddGroup) findViewById(R.id.pag);
        if (photoCore == null) {
            photoCore = new PhotoCore(pag, this);
            photoCore.setRatio(4, 3);
            photoCore.setResultHeight(500);
            photoCore.setResultWidth(500);
        }
        upd = new UploadProductDelegate(this);
        if (photoCoreDetail == null) {
            photoCoreDetail = upd.getPhotoCore();
        }
        pag.setPhotoCore(photoCore);
        if (hasProductId()) {
            ciProductTag.setVisibility(View.VISIBLE);
            ciProductActivity.setVisibility(View.VISIBLE);
            ciProductSecKill.setVisibility(View.VISIBLE);
            if (isInventory) {
                tvInventoryTitle.setText("库存");
            } else {
                String s = "库存 <font color=\"#ff0000\">*</font>";

                tvInventoryTitle.setText(Html.fromHtml(s));
            }
            ciProductActivity.setTitleText("促销");
            requestProductDetail();
        } else {
            ciProductTag.setVisibility(View.GONE);
            ciProductActivity.setVisibility(View.GONE);
            ciProductSecKill.setVisibility(View.GONE);
            productAddEntity = DataManager.getInstance().getProductAddEntity();
            if (productAddEntity != null) {
                productAddEntity.setTitle(getRecommendTitle());
            }
            initProduct();
            ciProductClassify.setContentText("");
            if (BaseApplication.getInstance().getMerchant().isCategoryLevelOne()) {
                productAddEntity.setStoreTopCategoryId(null);
                productAddEntity.setStoreTopCategoryName(null);
            } else {
                productAddEntity.setStoreCategoryId(null);
                productAddEntity.setStoreCategoryName(null);
            }
        }
        //临时
        if (type != null && "2".equals(type)) {
            ciProductActivity.setVisibility(View.GONE);
            ciProductSecKill.setVisibility(View.GONE);
        }
        if (!BaseApplication.getInstance().isCategoryLevelOne()) {
            ciProductClassify.setNotNull(true);
        } else {
            ciProductClassify.setNotNull(false);
        }
        ciProductClassify.setTitleText("分类");

        String type = productAddEntity.getType();
        if ("1".equals(type)) {//现货
            ciInDate.setVisibility(View.GONE);
            ciDateline.setVisibility(View.GONE);
        } else if ("2".equals(type)) {//预售
            ciInDate.setVisibility(View.VISIBLE);
            ciDateline.setVisibility(View.VISIBLE);
        }
        checkAuthNeedBind();
        requestTagList(true, false);
    }

    /**
     * 检测散货店铺权限
     */
    private void checkAuthNeedBind() {
        if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
            findViewById(R.id.fl_banner).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
            findViewById(R.id.fl_detail).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
            ciProductTitle.getEdInput().setEnabled(false);
            edInventory.setEnabled(false);
            edProductDescribe.setEnabled(false);

            tvDelete.setTextColor(Color.parseColor("#aaaaaa"));
            tvDraft.setTextColor(Color.parseColor("#aaaaaa"));
            tvBtn.setTextColor(Color.parseColor("#aaaaaa"));
            tvBtn.setBackgroundResource(R.drawable.btn_white_bg);
        }
    }

    private boolean hasProductId() {
        return (productId == null || "".equals(productId)) ? false : true;
    }

    private void initProduct() {
        if (productAddEntity == null) {
            finish();
            return;
        }
        //未开店的隐藏线上销售按钮
        MerChantInfo merChantInfo = BaseApplication.getInstance().getMerchant();
        //开店成功
        if (merChantInfo != null && merChantInfo.getStoreStatus() != null && merChantInfo.getStoreStatus().equals("2")) {

//            productAddEntity.setSaleChannelApp(true);
//            productAddEntity.setPurchaseIsSale(true);
        } else {
            // productAddEntity.setSaleChannelApp(false);
            productAddEntity.setPurchaseIsSale(false);
            rlOnlineSale.setVisibility(View.GONE);
        }
        Category name = productAddEntity.getName();
        if (name != null) {
            isCategoryType = name.isCategoryType();
        }
        if (productAddEntity.isPurchaseIsSale()) {
            ssOrder.setOpen(true);
        } else {
            ssOrder.setOpen(false);
        }
        if (productAddEntity.getProductParseDto() != null) {
            ciProductTitle.setContentText(productAddEntity.getProductParseDto().getTitle());
        }
        ciProductTitle.setSelectionLast();
        if (pinlei != null) {
            if (!moml) {
                ciProductSpec.setContentText(pinlei + "(非清真)");
            } else {
                ciProductSpec.setContentText(pinlei);
            }
        }

        if (productAddEntity.getProductParseDto() != null) {
            if (productAddEntity.getProductParseDto().isHalal()) {
                ciProductSpec.setContentText(productAddEntity.getProductParseDto().getCategoryiiiName());
            } else {
                //专卖不需要（非清真）
//            ciProductSpec.setContentText(getCategoryName() + "(非清真)");
                ciProductSpec.setContentText(productAddEntity.getProductParseDto().getCategoryiiiName() + "(非清真)");
            }
        }
        tvInventory.setText(productAddEntity.getChargeUnit());
        if (productAddEntity.hasPurchaseInfo()) {
            ciProductStock.setContentText("已填写");
        } else {
            ciProductStock.setContentText("");
        }
        if (!hasProductId()) {
            edInventory.setEnabled(false);
        }

        if (isInventory) {
            edInventory.setEnabled(false);
        }
        edInventory.setText(productAddEntity.getInventoryAmount());
        if (productAddEntity.getProductParseDto() != null) {
            edProductDescribe.setText(productAddEntity.getProductParseDto().getDescription());
        }
        updatePriceMoqView();
        List<Images> imagesBanner = productAddEntity.getImages();
        if (imagesBanner != null && imagesBanner.size() > 0) {
            for (int i = 0; i < imagesBanner.size(); i++) {
                Images images1 = imagesBanner.get(i);
                if (images1 != null && images1.isBanner() && i < 3) {
                    String imageUrl = images1.getPath();
                    if (imageUrl != null && !"".equals(imageUrl)) {
                        pag.addNetPhoto(imageUrl, images1.getAttachmentId());
                        isModify = true;
                    } else {
                        pag.addFilePhoto(images1.getFilePath(), images1.getImgId());
                    }
                }
            }
        }
        List<Images> imagesDetail = productAddEntity.getImagesDetail();
        if (imagesDetail != null && imagesDetail.size() > 0) {
            upd.setImgList(imagesDetail);
        }
        if (hasProductId()) {
            //我要买-拼货订单，选中一个交易成功的订单，点击转卖商品，品类字段应该可编缉，xx(非清真)不需要
            if (listType == 1 || listType == 2) {//下架商品也不能改品类
                ciProductSpec.setEditable(false);
                ciProductSpecName.setEditable(false);
            }
        }

        if ("1".equals(productAddEntity.getIfPromotion())) {
            ciProductActivity.setContentText("已填写");
        } else {
            ciProductActivity.setContentText("");
        }

        if ("1".equals(productAddEntity.getIfSeckill())) {
            ciProductSecKill.setContentText("已填写");
        } else {
            ciProductSecKill.setContentText("");
        }
        if (listType == 2) {
            if ("1".equals(productAddEntity.getIfPromotion())) {
                ciProductActivity.setVisibility(View.VISIBLE);
            } else {
                ciProductActivity.setVisibility(View.GONE);
            }
            if ("1".equals(productAddEntity.getIfSeckill())) {
                ciProductSecKill.setVisibility(View.VISIBLE);
            } else {
                ciProductSecKill.setVisibility(View.GONE);
            }
        }
        List<TagEntity> tags = productAddEntity.getTags();
        if (tags != null && tags.size() > 0) {
            ciProductTag.setContentText("已填写");
        } else {
            ciProductTag.setContentText("");
        }

        String classify = "";
        //一级
        if (BaseApplication.getInstance().getMerchant().isCategoryLevelOne()) {
            classify = productAddEntity.getStoreTopCategoryName();
        } else {
            classify = productAddEntity.getStoreCategoryName();
            if (classify == null || "".equals(classify)) {
                classify = productAddEntity.getCategoryName();
            }
        }

        if (isCategoryType) {
            ciProductSpecName.setVisibility(View.VISIBLE);
        } else {
            ciProductSpecName.setVisibility(View.GONE);
        }
        ciProductClassify.setContentText(classify);
        ciProductSpecName.setContentText(productAddEntity.getSpecies());
        updatePackageText(productAddEntity.getPackageStr());
        ciProductArea.setContentText(productAddEntity.getOrigin());
        if (listType == 3) {
            ciProductTag.setVisibility(View.GONE);
            ciProductActivity.setVisibility(View.GONE);
            ciProductSecKill.setVisibility(View.GONE);
            ciProductArea.setEditable(false);
        }
        String type = productAddEntity.getType();
        if ("2".equals(type)) {
            ciInDate.setContentText(productAddEntity.getDeliveryTime());
            ciDateline.setContentText(productAddEntity.getSaleDeadline());
        } else {
            ciInDate.setContentText("");
            ciDateline.setContentText("");
        }
    }

    private void updatePackageText(String s) {
        ciProductPackage.setContentText(productAddEntity.getPackageStr());
        if (s != null && !"".equals(s)) {
            rlPackage.setVisibility(View.GONE);
            tvPackageSize.setText(productAddEntity.getPackageSize());
            tvPackageUnit.setText(productAddEntity.getPackageUnitStr());
        } else {
            rlPackage.setVisibility(View.GONE);
        }
    }

    private void updatePriceMoqView() {
        String price = String.valueOf(productAddEntity.getPrice());
        if (price == null || "0.0".equals(price)) {
            ivPriceMoq.setVisibility(View.GONE);
            ciProductMoq.setVisibility(View.GONE);
            ciProductPrice.setContentText("");
            ciProductMoq.setContentText("");
        } else {
            ivPriceMoq.setVisibility(View.VISIBLE);
            ciProductMoq.setVisibility(View.VISIBLE);
            ciProductPrice.setContentText(productAddEntity.getPrice() + productAddEntity.getUnitPriceStr());
            ciProductPrice.setContentTextColor("#fd9626");
            if (productAddEntity.getProductSpecPrice() != null) {
                ciProductMoq.setContentText(productAddEntity.getProductSpecPrice().getMoq() + productAddEntity.getChargeUnit() + "起");
            }
            tvInventory.setText(productAddEntity.getChargeUnit());
        }
    }

    //品类-品名-品种-等级-品牌-产地-包装规格；
    private String getCategoryName() {
        StringBuilder sb = new StringBuilder();
        String s = productAddEntity.getNames();
        if (s != null && !"".equals(s)) {
            sb.append(s);
        }
        return sb.toString();
    }

    //标题生成规则：产地-品种-品类或者品名-(品牌)(等级)
    private String getRecommendTitle() {

        //品类【产地】【包装】
        StringBuilder sb = new StringBuilder();
        String ss = productAddEntity.getOrigin();
        if (ss != null && !"".equals(ss)) {
            sb.append(ss);
        }
        if (isCategoryType) {
            ss = productAddEntity.getSpecies();
            if (ss != null && !"".equals(ss)) {
                if (sb.length() > 0) {
                    sb.append("");
                    sb.append(ss);
                    sb.append("");
                } else {
                    sb.append(ss);
                }
            }
        } else {
            ss = productAddEntity.getNames();
            if (ss != null && !"".equals(ss)) {
                if (sb.length() > 0) {
                    sb.append("");
                    sb.append(ss);
                    sb.append("");
                } else {
                    sb.append(ss);
                }
            }
        }
        return sb.toString();
    }

    private boolean isCanPost() {
        boolean isCanPost = true;
        List<Images> images = pag.getImages();
        if (images == null || images.size() == 0) {
            toast("请上传封面图片");
            return false;
        }

        if (pag.isImageUploading()) {
            toast("封面图片正在上传");
            return false;
        }
        if (!isModify) {
            if (pag.isImageUploadFail()) {
                toast("封面图片上传失败,请重新上传");
                return false;
            }
        }
        if (ciProductTitle.isContentEmpty()) {
            toast("请填写商品标题");
            return false;
        }
        if (ciProductSpec.isContentEmpty()) {
            toast("请选择商品品类");
            return false;
        }
        if (isCategoryType && ciProductSpecName.isContentEmpty()) {
            toast("请选择商品品名");
            return false;
        }
//        if (!BaseApplication.getInstance().isCategoryLevelOne() && ciProductClassify.isContentEmpty()) {
//            toast("请选择商品分类");
//            return false;
//        }
        if (ciProductPackage.isContentEmpty()) {
            toast("请填写商品包装");
            return false;
        }

        if (ciProductPrice.isContentEmpty()) {
            toast("请填写价格及起订量");
            return false;
        }
        if (ciProductStock.isContentEmpty()) {
            toast("请填写进货信息");
            return false;
        }
        if (!isInventory && TextUtils.isEmpty(edInventory.getText())) {
            toast("请填写库存");
            return false;
        }
        String type = productAddEntity.getType();


        if ("2".equals(type) && (
                ciInDate.isContentEmpty()

        )) {
            toast("请选择预计送达时间");
            return false;

        }
        if ("2".equals(type) && (
                ciDateline.isContentEmpty()
        )) {
            toast("请选择预售截止时间");
            return false;
        }
        if ("2".equals(type) &&
                !isPreDateLegal(ciInDate.getContentText(), ciDateline.getContentText(), "")
                ) {
            return false;
        }

        if (TextUtils.isEmpty(edProductDescribe.getText())) {
            toast("请填写商品简介");
            return false;
        }
        List<Images> images1 = upd.getImages();
        if (images1 != null && images1.size() > 0 && upd.isUploadNotSuccess()) {
            toast("商品详情图片未上传完成");
            return false;
        }
        return isCanPost;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(Constant.TYPE, type);
        outState.putString("productId", productId);
        outState.putBoolean("is_first", isAddProduct);
        outState.putBoolean("isCategoryType", isCategoryType);
        outState.putInt("listType", listType);
        if (productAddEntity != null) {
            outState.putString("dataProduct", new Gson().toJson(productAddEntity));
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.rightbtn:
                help();
                break;
            case R.id.v_receive:
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    if (ssOrder.isOpen()) {
                        ssOrder.setOpen(false);
                        ssOrder.setState(false);

                        if (productAddEntity != null)
                            productAddEntity.setPurchaseIsSale(false);

                    } else {
                        ssOrder.setOpen(true);
                        ssOrder.setState(true);
                        if (productAddEntity != null)
                            productAddEntity.setPurchaseIsSale(true);
                    }
                }
                break;
            case R.id.ci_product_name:
                break;
            case R.id.ci_product_spec_name://品名
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    intoSpecName();
                }
                break;
            case R.id.ci_product_classify://分类
                intoClassify();
                break;
            case R.id.ci_product_package://包装
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    intoPackage();
                }
                break;
            case R.id.ci_product_area://产地
                intoArea();
                break;
            case R.id.ci_product_tag://商品标签
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    intoProductTag();
                }
                break;
            case R.id.ci_product_activity://商品活动
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    if (ciProductPrice.isContentEmpty()) {
                        toast("请先填写价格及起订量");
                        return;
                    }
                    intoProductActivity();
                }
                break;
            case R.id.ci_product_seckill://商品秒杀
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    if (ciProductPrice.isContentEmpty()) {
                        toast("请先填写价格及起订量");
                        return;
                    }
                    intoProductSecKill();
                }
                break;
            case R.id.ci_product_price:
            case R.id.ci_product_moq:
            case R.id.iv_product_price_flag:
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    intoPriceMoqView();
                }
                break;
            case R.id.ci_product_stock://进货信息
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    intoStock();
                }
                break;
            case R.id.ci_product_spec://商品规格
/*                if(listType == 1 || listType == 2)
                    return;*/
                intoProductCategory();
                break;
            case R.id.tv_btn://
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    if (!isCanPost()) {
                        return;
                    }
                    postProduct();
                }
                break;
            case R.id.tv_draft://
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    postProductDraft();
                }
                break;
            case R.id.tv_delete://
                if (BaseApplication.getInstance().getMerchant().isAuthNeedBind()) {
                    T.toast("暂无权限");
                } else {
                    delete(productId);
                }
                break;

            case R.id.ci_in_date:
                String t2 = ciInDate.getContentText();
                openInDate(t2);
                break;
            case R.id.ci_dateline:
                String t3 = ciDateline.getContentText();
                openDateline(t3);
                break;
        }
    }

    private void openInDate(String time) {
        TimePickerDialog timeDialog = new TimePickerDialog(this);
        timeDialog.setOnPositiveClickListener(new TimePickerDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(int index, String data) {
                ciInDate.setContentText(data);
            }
        });
        timeDialog.setTitle("预计送达时间");
        calculatePreInDate(timeDialog);
        timeDialog.setCurrentDate(time);
        timeDialog.show();
    }

    private void calculatePreInDate(TimePickerDialog timeDialog) {
        String productDate = "";
        String productDateLine = ciDateline.getContentText();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String time = null;
            int c = DateUtil.compare(productDate, productDateLine);
            // -3,time1,time2都为空，1,time2大，-1,time1大，0,一样大 ，-2,异常
            if (c == 1) {
                time = productDateLine;
            } else if (c == -1) {
                time = productDate;
            }
            Date date = new Date();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.DATE, 1);
            date.setTime(calendar.getTimeInMillis());
            String today = sdf.format(date);
            c = DateUtil.compare(time, today);
            if (c == 1) {
                time = today;
            } else if (c == -1) {
            }
            if (time != null && !"".equals(time)) {
                long timeMill = sdf.parse(time).getTime();
                calendar.setTimeInMillis(timeMill);
                int dx = 0;
                int cx = DateUtil.compare(productDate, productDateLine);
                // -3,time1,time2都为空，1,time2大，-1,time1大，0,一样大 ，-2,异常
                if (cx == 1) {
                    dx = 1;
                } else if (c == 0) {
                }
                int sy = calendar.get(Calendar.YEAR);
                int sm = calendar.get(Calendar.MONTH) + 1;
                int sd = calendar.get(Calendar.DAY_OF_MONTH) + dx;
                timeDialog.setStartYear(sy);
                timeDialog.setStartMonth(sm);
                timeDialog.setStartDay(sd);
                calendar.add(Calendar.MONTH, 48);
                int ey = calendar.get(Calendar.YEAR);
                int em = calendar.get(Calendar.MONTH) + 1;
                int ed = calendar.get(Calendar.DAY_OF_MONTH);
                timeDialog.setEndYear(ey);
                timeDialog.setEndMonth(em);
                timeDialog.setEndDay(ed);
                if (ey < sy) {
                    sy = ey;
                }
                if (sy == ey && em < sm) {
                    sm = em;
                }
                if (sy == ey && em == sm && ed < sd) {
                    sd = ed;
                }
                timeDialog.setStartYear(sy);
                timeDialog.setStartMonth(sm);
                timeDialog.setStartDay(sd);

            } else {
                calendar.setTimeInMillis(System.currentTimeMillis());
                calendar.add(Calendar.DATE, 1);
                int sy = calendar.get(Calendar.YEAR);
                int sm = calendar.get(Calendar.MONTH) + 1;
                int sd = calendar.get(Calendar.DAY_OF_MONTH);
                timeDialog.setStartYear(sy);
                timeDialog.setStartMonth(sm);
                timeDialog.setStartDay(sd);

                calendar.add(Calendar.MONTH, 24);
                int ey = calendar.get(Calendar.YEAR);
                int em = calendar.get(Calendar.MONTH) + 1;
                int ed = calendar.get(Calendar.DAY_OF_MONTH);
                timeDialog.setEndYear(ey);
                timeDialog.setEndMonth(em);
                timeDialog.setEndDay(ed);
                if (ey < sy) {
                    sy = ey;
                }
                if (sy == ey && em < sm) {
                    sm = em;
                }
                if (sy == ey && em == sm && ed < sd) {
                    sd = ed;
                }
                timeDialog.setStartYear(sy);
                timeDialog.setStartMonth(sm);
                timeDialog.setStartDay(sd);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void openDateline(String time) {
        TimePickerDialog timeDialog = new TimePickerDialog(this);
        timeDialog.setTitle("预售截止时间");
        timeDialog.setOnPositiveClickListener(new TimePickerDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(int index, String data) {
                ciDateline.setContentText(data);
            }
        });
        calculateProductDataLine(timeDialog);
        timeDialog.setCurrentDate(time);
        timeDialog.show();
    }

    private void calculateProductDataLine(TimePickerDialog timeDialog) {
        String arrivalDate = ciInDate.getContentText();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //截止时间
            if (arrivalDate != null && !"".equals(arrivalDate)) {
                long timeMill = sdf.parse(arrivalDate).getTime();
                calendar.setTimeInMillis(timeMill);
                int ey = calendar.get(Calendar.YEAR);
                int em = calendar.get(Calendar.MONTH) + 1;
                int ed = calendar.get(Calendar.DAY_OF_MONTH) - 1;
                timeDialog.setEndYear(ey);
                timeDialog.setEndMonth(em);
                timeDialog.setEndDay(ed);

                calendar.setTimeInMillis(System.currentTimeMillis());
                int sy = calendar.get(Calendar.YEAR);
                int sm = calendar.get(Calendar.MONTH) + 1;
                int sd = calendar.get(Calendar.DAY_OF_MONTH);

                if (ey < sy) {
                    sy = ey;
                }
                if (sy == ey && em < sm) {
                    sm = em;
                }
                if (sy == ey && em == sm && ed < sd) {
                    sd = ed;
                }
                timeDialog.setStartYear(sy);
                timeDialog.setStartMonth(sm);
                timeDialog.setStartDay(sd);
            } else {
                calendar.setTimeInMillis(System.currentTimeMillis());
                int sy = calendar.get(Calendar.YEAR);
                int sm = calendar.get(Calendar.MONTH) + 1;
                int sd = calendar.get(Calendar.DAY_OF_MONTH);

                calendar.add(Calendar.MONTH, 24);
                int ey = calendar.get(Calendar.YEAR);
                int em = calendar.get(Calendar.MONTH) + 1;
                int ed = calendar.get(Calendar.DAY_OF_MONTH);
                timeDialog.setEndYear(ey);
                timeDialog.setEndMonth(em);
                timeDialog.setEndDay(ed);
                if (ey < sy) {
                    sy = ey;
                }
                if (sy == ey && em < sm) {
                    sm = em;
                }
                if (sy == ey && em == sm && ed < sd) {
                    sd = ed;
                }
                timeDialog.setStartYear(sy);
                timeDialog.setStartMonth(sm);
                timeDialog.setStartDay(sd);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public boolean isPreDateLegal(String arrivalDate, String saleDeadline, String productDate) {
        //预计送达时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            int c = DateUtil.compare(arrivalDate, saleDeadline);
            // -3,time1,time2都为空，1,time2大，-1,time1大，0,一样大 ，-2,异常
            if (c == -1 || c == 0) {
                Date date = new Date(System.currentTimeMillis());
                String format = sdf.format(date);
                c = DateUtil.compare(arrivalDate, format);
                if (c == -1) {
                    c = DateUtil.compare(saleDeadline, format);
                    if (c == -1 || c == 0) {
                        if (productDate == null || "".equals(productDate)) {
                            return true;
                        }
                        c = DateUtil.compare(arrivalDate, productDate);
                        if (c == -1 || c == 0) {
                            return true;
                        }
                        toast("生产日期不能晚于预计送达时间");
                        return false;
                    }
                    toast("预售截止时间不能早于今天");
                    return false;

                }
                toast("预计送达时间要晚于今天");
                return false;
            } else {
                toast("预售截止时间不能晚于预计送达时间");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //品名
    private void intoSpecName() {
        if (productAddEntity != null) {
            Intent intent = new Intent(this, ProductAddOtherActivity.class);
            intent.putExtra("page_type", "5");
            intent.putExtra("content", productAddEntity.getSpecies());
            //三级
            intent.putExtra("nameId", productAddEntity.getNameId());
            startActivityForResult(intent, 0x617);
        }
    }

    //产地
    private void intoArea() {
        if (productAddEntity != null) {
            Intent intent = new Intent(this, ProductAddOtherActivity.class);
            intent.putExtra("page_type", "3");
            intent.putExtra("content", productAddEntity.getOrigin());
            //三级
            intent.putExtra("nameId", productAddEntity.getNameId());
            startActivityForResult(intent, 0x9520);
        }
    }

    //包装
    private void intoPackage() {
        String tagPackageStr = null;
        if (hasProductId()) {
            if (tagPackage != null) {
                tagPackageStr = new Gson().toJson(tagPackage);
            }
        } else {
            tagPackageStr = getIntent().getStringExtra("tagPackage");
        }
        if (tagPackageStr != null && !"".equals(tagPackageStr)) {
            intoPack(tagPackageStr);
        } else {
            requestTagList(false, true);
        }
    }

    private void intoPack(String tagPackageStr) {
        Intent intent = new Intent(this, ProductPackageActivity.class);
        intent.putExtra("unit", productAddEntity.getPackageUnit());
        intent.putExtra("packageSize", productAddEntity.getPackageSize());
        intent.putExtra("container", productAddEntity.getPackageContainer());
        intent.putExtra("weight", productAddEntity.getWeight());
        intent.putExtra("tagPackage", tagPackageStr);
        if (hasProductId()) {//已上架商品包装业务变更，可以调整第二行重量，但是不可以调整第一行包装
            //如果是已下架，不能修改包装(修复千年bug)
            if (listType == 1 || listType == 2) {
                intent.putExtra("isAlready", true);
            }
        }
        startActivityForResult(intent, 0x49);
    }

    //分类
    private void intoClassify() {
        Intent intent = new Intent(this, ProductClassifyManagerActivity.class);
        intent.putExtra("type", 1);
        intent.putExtra("categoryName", productAddEntity.getCategoryName());
        intent.putExtra("categoryId", productAddEntity.getCategoryId());
        if (!BaseApplication.getInstance().getMerchant().isCategoryLevelOne()) {
            intent.putExtra("topCategoryId", productAddEntity.getTopCategoryId());
            intent.putExtra("storeCategoryOnly", true);
        } else {
            intent.putExtra("storeCategoryId", productAddEntity.getStoreTopCategoryId());
        }
        startActivityForResult(intent, 0x9502);
    }

    private void intoProductSecKill() {
        String ifSeckill = productAddEntity.getIfSeckill();
        if (hasProductId() && "1".equals(ifSeckill)) {
            Intent intent = new Intent(this, ProductPromotionListActivity.class);
            intent.putExtra("productId", productId);
            intent.putExtra("chargeUnit", productAddEntity.getChargeUnit());
            intent.putExtra("incr", productAddEntity.getIncr());
            intent.putExtra("moq", productAddEntity.getMoq());
            intent.putExtra("inventory", productAddEntity.getInventoryAmount());
            intent.putExtra("type", "2");
            if (listType == 2) {
                intent.putExtra("productStatus", "0");
            }
            startActivityForResult(intent, 0x1999);
        } else {
            Intent intent = new Intent(this, ProductSecKillActivity.class);
            intent.putExtra("chargeUnit", productAddEntity.getChargeUnit());
            intent.putExtra("incr", productAddEntity.getIncr());
            intent.putExtra("moq", productAddEntity.getMoq());
            intent.putExtra("inventory", productAddEntity.getInventoryAmount());
            intent.putExtra("price", productAddEntity.getPrice() + "");
            if (hasProductId()) {
                intent.putExtra("isEdit", true);
            }
            intent.putExtra("promotion", new Gson().toJson(productAddEntity.getSecKill()));
            startActivityForResult(intent, 0x1947);
        }
    }

    //促销活动
    private void intoProductActivity() {
//        1促销2秒杀
        String ifPromotion = productAddEntity.getIfPromotion();
        if (hasProductId() && "1".equals(ifPromotion)) {
            Intent intent = new Intent(this, ProductPromotionListActivity.class);
            intent.putExtra("productId", productId);
            intent.putExtra("type", "1");
            intent.putExtra("chargeUnit", productAddEntity.getChargeUnit());
            intent.putExtra("incr", productAddEntity.getIncr());
            intent.putExtra("moq", productAddEntity.getMoq());
            intent.putExtra("inventory", productAddEntity.getInventoryAmount());
            intent.putExtra("price", productAddEntity.getPrice() + "");
            if (listType == 2) {
                intent.putExtra("productStatus", "0");
            }
            startActivityForResult(intent, 0x1999);
        } else {
            Intent intent = new Intent(this, ProductPromotionActivity.class);
            intent.putExtra("chargeUnit", productAddEntity.getChargeUnit());
            intent.putExtra("incr", productAddEntity.getIncr());
            intent.putExtra("moq", productAddEntity.getMoq());
            intent.putExtra("inventory", productAddEntity.getInventoryAmount());
            intent.putExtra("price", productAddEntity.getPrice() + "");
            intent.putExtra("promotion", new Gson().toJson(productAddEntity.getPromotion()));
            if (hasProductId()) {
                intent.putExtra("isEdit", true);
            }
            startActivityForResult(intent, 0x1948);
        }
    }

    //商品标签
    private void intoProductTag() {
        if (tagPackage != null) {
            intoTag();
        } else {
            requestTagList(false, false);
        }
    }

    private void intoTag() {
        Intent intent = new Intent(this, ProductTagActivity.class);
        intent.putExtra("type", productAddEntity.getType());
        intent.putExtra("productId", productAddEntity.getId());
        if (hasProductId()) {
            intent.putExtra("isEdit", true);
            if (tagPackage != null) {
                intent.putExtra("tagPackage", new Gson().toJson(tagPackage));
            }
        } else {
            intent.putExtra("tagPackage", getIntent().getStringExtra("tagPackage"));
        }
        List<TagEntity> tags = productAddEntity.getTags();
        if (tags != null && tags.size() > 0) {
            intent.putExtra("tags", new Gson().toJson(tags));
        }
        startActivityForResult(intent, 0x1978);
    }

    CustomDialog.Builder builder;

    //保存为草稿
    private void postProductDraft() {
        if (!isCanPost()) {
            return;
        }
        if (builder == null) {
            builder = new CustomDialog.Builder(this);
        }
        String s = "是否保存为草稿";
        //上下架，1上架列表，2下架列表,0,草稿,4审核
        if (listType == 1) {
            s = "是否保存";
        } else if (listType == 2) {
            s = "是否保存";
        } else if (listType == 0) {
            s = "是否保存";
        }
        builder.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        dialog.dismiss();
                        int status = productAddEntity.getStatus();
                        Log.e("status", status + "");
                        save(status);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框
        builder.create().show();
    }

    private void inventoryDialog(StatusEntity responseElement) {
        if (responseElement == null) {
            return;
        }
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        String s = "";
        final boolean isPormotionFail = responseElement.isPromotionFail();
        final boolean isSecKillFail = responseElement.isSeckillFail();
        if (isPormotionFail && isSecKillFail) {
            s = "库存数量小于当前待促销及秒杀活动数量之和，活动是否继续？";
        } else if (isPormotionFail && !isSecKillFail) {
            s = "库存数量小于当前促销数量，活动是否继续？";
        } else if (!isPormotionFail && isSecKillFail) {
            s = " 库存数量小于当前秒杀活动数量，活动是否继续？";
        }
        builder.setTitleVisible(false).setMessage(s);//设置显示的内容
        if (isSecKillFail) {
            builder.setPositiveButton("结束秒杀", new DialogInterface.OnClickListener() {//添加确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                    save(true, 2);
                    dialog.dismiss();
                }
            });
        }
        if (isPormotionFail) {
            builder.setMidButton("结束促销", new DialogInterface.OnClickListener() {//添加确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                    save(true, 1);
                    dialog.dismiss();
                }
            });
        }
        builder.setNegativeButton("继续", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                save(true, 0);
                dialog.dismiss();
            }
        });//在按键响应事件中显示此对话框
        builder.create().show();
    }

    //上架商品
    private void postProduct() {
        if (builder == null) {
            builder = new CustomDialog.Builder(this);
        }
        String s = "是否确认上架商品";
        builder.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        save(1);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框
        builder.create().show();
    }

    private void saveProduct() {
        List<Images> images = pag.getImages();
        List<Images> images1 = upd.getImages();
        productAddEntity.setImagesBanner(images);
        productAddEntity.setImagesDetail(images1);
        productAddEntity.reSortImages();
        productAddEntity.setTitle(ciProductTitle.getContentText());
        productAddEntity.setInventoryAmount(edInventory.getText().toString());
        productAddEntity.setDescription(edProductDescribe.getText().toString());
        String type = productAddEntity.getType();
//        PurchaseInfo purchase = productAddEntity.getPurchase();
//        //这个地方是把库存传过来了
//        if (purchase==null){
//            purchase=new PurchaseInfo();
//            purchase.setQuantity(Integer.parseInt(productAddEntity.getInventoryAmount()));
//        }else {
//            purchase.setQuantity(Integer.parseInt(productAddEntity.getInventoryAmount()));
//        }
//        productAddEntity.setPurchase(purchase);
        if ("2".equals(type)) {
            productAddEntity.setDeliveryTime(ciInDate.getContentText());
            productAddEntity.setSaleDeadline(ciDateline.getContentText());
        } else {
            productAddEntity.setDeliveryTime(null);
            productAddEntity.setSaleDeadline(null);
        }
        if (productId != null && !"".equals(productId) && listType != 3) {
            requestProductModify();
        } else {
            requestProductAdd();
        }
    }

    private void save(int status) {
        productAddEntity.setSkip(false);
        productAddEntity.setStatus(status);
        productAddEntity.setPromotionTypes(null);
        saveProduct();
    }

    private void save(boolean isSkip, int promotionType) {
        productAddEntity.setSkip(isSkip);
        if (promotionType != 1 && promotionType != 2) {
            productAddEntity.setPromotionTypes(null);
        } else {
            ArrayList<Integer> strings = new ArrayList<>();
            strings.add(promotionType);
            productAddEntity.setPromotionTypes(strings);
        }
        saveProduct();
    }

    private void intoProductCategory() {
        Intent intent = new Intent(this, ProductAddCategoryActivity.class);
        if (hasProductId()) {
            intent.putExtra(Constant.TYPE, productAddEntity.getType());
            intent.putExtra("is_first", false);
            intent.putExtra("is_draft", true);
            intent.putExtra("productAddEntity", new Gson().toJson(productAddEntity));
            startActivityForResult(intent, 0x1894);
        } else {
            intent.putExtra("is_first", true);
            intent.putExtra("isCategoryType", isCategoryType);
            intent.putExtra("is_reset_category", true);
            productAddEntity.setInventoryAmount(edInventory.getText().toString());
            productAddEntity.setDescription(edProductDescribe.getText().toString());
            String type = productAddEntity.getType();
            if ("2".equals(type)) {
                productAddEntity.setDeliveryTime(ciInDate.getContentText());
                productAddEntity.setSaleDeadline(ciDateline.getContentText());
            } else {
                productAddEntity.setDeliveryTime(null);
                productAddEntity.setSaleDeadline(null);
            }
            intent.putExtra("productAddEntity", new Gson().toJson(productAddEntity));
            if (productAddEntity != null) {
                /*图片信息保存*/
                List<Images> imagesBanner = pag.getImages();
                List<Images> imagesDetail = upd.getImages();
                if (imagesBanner != null && imagesBanner.size() > 0)
                    intent.putExtra("imagesBanner", new Gson().toJson(imagesBanner));
                if (imagesDetail != null && imagesDetail.size() > 0)
                    intent.putExtra("imagesDetail", new Gson().toJson(imagesDetail));
                startActivity(intent);
            }
        }
    }

    private void intoPriceMoqView() {
        if (ciProductPackage.isContentEmpty()) {
            toast("请先填写包装");
            return;
        }
        Intent intent = new Intent(this, ProductAddPriceMoqActivity.class);
        intent.putExtra("type", 1);
        intent.putExtra("productId", productId);
        intent.putExtra("moq", productAddEntity.getMoq());
        if (listType == 1 && isModify1) {
            intent.putExtra("incr", saveIncr);
        } else {
            intent.putExtra("incr", productAddEntity.getIncr());
        }
        intent.putExtra("price", productAddEntity.getPrice() + "");
        if (listType == 1) {
            intent.putExtra("unit", saveUnit);
        } else {
            intent.putExtra("unit", productAddEntity.getChargeUnit());
        }
        intent.putExtra("packageContainer", productAddEntity.getPackageContainer());
        intent.putExtra("packageUnit", productAddEntity.getPackageUnit());
        intent.putExtra("packageSize", productAddEntity.getPackageSize());
        intent.putExtra("weight", productAddEntity.getWeight());
        intent.putExtra("listType", listType + "");
//        intent.putExtra("weight", productAddEntity.getWeight());
//        if (listType == 0) {//草稿
//            intent.putExtra("priceUnit", productAddEntity.getPriceUnitStr());
//        } else {
//            intent.putExtra("priceUnit", productAddEntity.getPriceUnit());
//        }
        intent.putExtra("priceUnit", productAddEntity.getPriceUnit());

        intent.putExtra("productPriceUnit", getProductPriceUint(productAddEntity.getPackageUnit(), productAddEntity.getPackageContainer()));
        Log.e("productPriceUnit", "productPriceUnit:" + getProductPriceUint(productAddEntity.getPackageUnit(), productAddEntity.getPackageContainer()));
        if (type != null && "1".equals(type)) {
            //现售
            intent.putExtra("saleType", 1);
        } else if (type != null && "2".equals(type)) {
            //预售
            intent.putExtra("saleType", 2);
        }
        startActivityForResult(intent, 0x1892);
    }

    private void intoStock() {
        Intent intent = new Intent(this, ProductAddStockActivity.class);
        PurchaseInfo purchase = productAddEntity.getPurchase();
        if (purchase != null) {
            intent.putExtra("PurchaseInfo", new Gson().toJson(purchase));
        }

        intent.putExtra("isFrom", getIntent().getStringExtra("isFrom"));
        intent.putExtra("UnitPrice", getIntent().getStringExtra("UnitPrice"));
        intent.putExtra("type", productAddEntity.getType());
        intent.putExtra("orderId", orderId);
        intent.putExtra("productId", productAddEntity.getId());
        intent.putExtra("chargeUnit", productAddEntity.getChargeUnit());
        if (hasProductId()) {
            intent.putExtra("isEdit", true);
        }
        startActivityForResult(intent, 0x1921);
    }

    boolean isNeedRefresh;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x1921 && resultCode == RESULT_OK) {//进货信息
            isModifyJinHuo = data.getBooleanExtra("isModifyJinHuo", false);
            String result = data.getStringExtra("result");
            if (result != null && !"".equals(result)) {
                productAddEntity.setPurchase(null);
                PurchaseInfo pi = new Gson().fromJson(result, PurchaseInfo.class);
                pi.setId(null);
                productAddEntity.setPurchase(pi);
                ciProductStock.setContentText("已填写");
                if (!hasProductId() || isInventory) {
                    edInventory.setText(pi.getQuantity() + "");
                }
            } else {
                productAddEntity.setPurchase(null);
                ciProductStock.setContentText("");
            }
        } else if (requestCode == 0x1892 && resultCode == RESULT_OK) {//进货信息
            String price = data.getStringExtra("price");
            String chargeUnit = data.getStringExtra("unit");
            String moq = data.getStringExtra("moq");

            if (price != null && !"".equals(price)) {

                productAddEntity.setChargeUnit(chargeUnit);
                productAddEntity.setPrice(Float.parseFloat(price));
                productAddEntity.setMoq(moq);
                ciProductMoq.setContentText(moq + productAddEntity.getChargeUnit() + "起");
            } else {
                productAddEntity.setChargeUnit("");
                productAddEntity.setPrice(0);
                productAddEntity.setMoq("");
            }
            updatePriceMoqView();

        } else if (requestCode == 0x1978 && resultCode == RESULT_OK) {//进货信息
            String tagStr = data.getStringExtra("tags");
            if (tagStr != null && !"".equals(tagStr)) {

                List<TagEntity> tags = new Gson().fromJson(tagStr, new TypeToken<List<TagEntity>>() {
                }.getType());
                if (tags != null && tags.size() == 0) {
                    productAddEntity.setTags(null);
                    ciProductTag.setContentText("");
                } else {
                    productAddEntity.setTags(tags);
                    ciProductTag.setContentText("已填写");
                }
            } else {
                productAddEntity.setTags(null);
                ciProductTag.setContentText("");
            }
        } else if (requestCode == 0x1947 && resultCode == RESULT_OK) {//秒杀
            String tagStr = data.getStringExtra("promotion");
            if (tagStr != null && !"".equals(tagStr)) {
                Promotion promotion = new Gson().fromJson(tagStr, Promotion.class);
                if (promotion != null && promotion.getType() != null) {
                    productAddEntity.setPromotion(promotion);
                    ciProductSecKill.setContentText("已填写");
                } else {
                    productAddEntity.setPromotionList(null);
                    ciProductSecKill.setContentText("");
                }
            } else {
                productAddEntity.setPromotionList(null);
                ciProductSecKill.setContentText("");
            }
        } else if (requestCode == 0x1948 && resultCode == RESULT_OK) {//秒杀
            String tagStr = data.getStringExtra("promotion");
            if (tagStr != null && !"".equals(tagStr)) {
                Promotion promotion = new Gson().fromJson(tagStr, Promotion.class);
                if (promotion != null && promotion.getType() != null) {
                    productAddEntity.setPromotion(promotion);
                    ciProductActivity.setContentText("已填写");
                } else {
                    productAddEntity.setPromotionList(null);
                    ciProductActivity.setContentText("");
                }
            } else {
                productAddEntity.setPromotionList(null);
                ciProductActivity.setContentText("");
            }
        } else if (requestCode == 0x1999 && resultCode == RESULT_OK) {//秒杀
            isNeedRefresh = data.getBooleanExtra("isNeedRefresh", false);
        } else if (requestCode == 0x49 && resultCode == RESULT_OK) {//
            //包装
            String packageSize = data.getStringExtra("packageSize");
            String unit = data.getStringExtra("unit");
            String chargeUnit = data.getStringExtra("chargeUnit");
            String container = data.getStringExtra("container");
            String weight = data.getStringExtra("weight");
            String priceUnit = data.getStringExtra("priceUnit");
            String recommendTitle = getRecommendTitle();
            String contentText = ciProductTitle.getContentText();

            productAddEntity.setPackageSize(packageSize);
            productAddEntity.setPackageUnit(unit);
            productAddEntity.setPackageContainer(container);
            productAddEntity.setWeight(weight);
            if (listType == 1) {
                chargeUnit = saveUnit;
            }
            productAddEntity.setChargeUnit(chargeUnit);
            productAddEntity.setPriceUnit(priceUnit);
            isModify1 = data.getBooleanExtra("isModify", false);
            saveIncr = productAddEntity.getIncr();
            updatePackageText(productAddEntity.getPackageStr());

            if (contentText != null && contentText.equals(recommendTitle)) {
                ciProductTitle.setContentText(getRecommendTitle());
                ciProductTitle.setSelectionLast();
            }
//            productAddEntity.setPrice(0);
//            productAddEntity.setMoq("");
//            updatePriceMoqView();
        } else if (requestCode == 0x617 && resultCode == RESULT_OK) {//
            //品名
            String result = data.getStringExtra("result");
            if (result == null || "".equals(result)) {
                result = null;
            }
            String recommendTitle = getRecommendTitle();
            String contentText = ciProductTitle.getContentText();
            productAddEntity.setSpecies(result);
            ciProductSpecName.setContentText(result);
            if (contentText != null && contentText.equals(recommendTitle)) {
                ciProductTitle.setContentText(getRecommendTitle());
                ciProductTitle.setSelectionLast();
            }
        } else if (requestCode == 0x9520 && resultCode == RESULT_OK) {//
            //产地
            String result = data.getStringExtra("result");
            if (result == null || "".equals(result)) {
                result = null;
            }
            String recommendTitle = getRecommendTitle();
            String contentText = ciProductTitle.getContentText();
            productAddEntity.setOrigin(result);
            ciProductArea.setContentText(result);
            if (contentText != null && contentText.equals(recommendTitle)) {
                ciProductTitle.setContentText(getRecommendTitle());
                ciProductTitle.setSelectionLast();
            }
        } else if (requestCode == 0x9502 && resultCode == RESULT_OK) {//
            String storeCategoryName = data.getStringExtra("storeCategoryName");
            String storeCategoryId = data.getStringExtra("storeCategoryId");
            boolean isPlatType = data.getBooleanExtra("isPlatType", false);
            productAddEntity.setPlatType(isPlatType);
            productAddEntity.setStoreCategoryId(null);
            productAddEntity.setStoreCategoryName(null);
            productAddEntity.setStoreTopCategoryId(null);
            productAddEntity.setStoreTopCategoryName(null);
            //平台
            if (isPlatType) {
            } else {
                //一级分类
                if (BaseApplication.getInstance().getMerchant().isCategoryLevelOne()) {
                    productAddEntity.setStoreTopCategoryId(storeCategoryId);
                    productAddEntity.setStoreTopCategoryName(storeCategoryName);
                } else {
                    productAddEntity.setStoreCategoryId(storeCategoryId);
                    productAddEntity.setStoreCategoryName(storeCategoryName);
                }
            }

            ciProductClassify.setContentText(storeCategoryName);

        } else if (requestCode == 0x1894 && resultCode == RESULT_OK) {
            if (data != null) {
                String s = data.getStringExtra("productAddEntity");
                if (s != null && !"".equals(s))
                    this.productAddEntity = new Gson().fromJson(s, ProductAddEntity.class);
            }
            //我要买，发布现货要修改标题by tony
            if (productAddEntity != null) {
                productAddEntity.setTitle(productAddEntity.getNames());
            }

            Log.e("productAddEntity", "productAddEntity:" + productAddEntity);
            initProduct();
        }

        if (pag.isSelect()) {
            photoCore.onResult(requestCode, resultCode, data);
        } else if (upd.isSelect()) {
            photoCoreDetail.onResult(requestCode, resultCode, data);
        }
    }

    private void requestProductAdd() {
        RequestEntitySupply<ProductAddEntity> RequestEntityMapSupply = new RequestEntitySupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_add);

        if (listType == 3) {
            productAddEntity.initWeight();
        }
        RequestEntityMapSupply.setParameters(productAddEntity);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_add, onProductAddRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductAddRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                intoProductList();
            } else {
                if (responseElement.isPromotionOrSeckillFail()) {
                    inventoryDialog(responseElement);
                } else if (productAddEntity.getStatus() == 0) {
                    toast("保存失败");
                } else {
                    toast("上架失败");
                }
            }

        }
    };

    private void intoProductList() {
        if (getIntent().getStringExtra("isSpotSearch") != null && getIntent().getStringExtra("isSpotSearch").equals("isSpotSearch")) {
            Intent intent = new Intent(this, SpotGoodsSearchActivity.class);
            if (productAddEntity.getStatus() == 0) {//草稿
                intent.putExtra("status", "0");
            }
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, ProductActivity.class);
            if (productAddEntity.getStatus() == 0) {
                intent.putExtra("status", "0");
            } else if (productAddEntity.getStatus() == 1) {
                if (type != null && "2".equals(type)) {
                    //预售
                    intent.putExtra("status", "2");
                }
            }
            if (listType == 3) {
                intent.putExtra("productType", 1);//现货
            }
            if (productAddEntity.getStatus() == 1) {
                intent.putExtra("status", "1");
            }
            startActivity(intent);
        }
        finish();
    }


    private void requestProductModify() {
        RequestEntitySupply<ProductAddEntity> RequestEntityMapSupply = new RequestEntitySupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_modify);
        productAddEntity.setProductSpecId(productId);
        if (!isModifyJinHuo) {
            productAddEntity.setPurchase(null);
        }
        RequestEntityMapSupply.setParameters(productAddEntity);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_modify, onProductModifyRequestListener);
    }

    private OnRequestListener<StatusEntity> onProductModifyRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                intoProductList();
            } else {
                if (responseElement.isPromotionOrSeckillFail()) {
                    inventoryDialog(responseElement);
                } else {
                    //没有数据
                    toast("修改失败");
                }
            }
        }
    };


    public void requestProductDetail() {
        RequestEntityMapSupply re = new RequestEntityMapSupply();
        if (orderId != null) {
            //转卖商品详情 pm-supply/buy/product/load
 /*           re.setCmd("supplier/product/load");
            re.putParameter("productId", productId);
            re.putParameter("orderId", orderId);
            request(re, "supplier/product/load", onProductDetailRequestListener);*/
            //转卖商品详情 pm-supply/buy/product/load
            re.setCmd(BuyerConstant.CMD_BUYER_BUY_PRODUCT_LOAD);
            re.putParameter("productSpecId", productId);
            re.putParameter("orderId", orderId);
            requestBuyer(re, BuyerConstant.CMD_BUYER_BUY_PRODUCT_LOAD, onProductDetailRequestListener);

        } else {
            re.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_load4supplier);
            re.putParameter("productSpecId", productId);
//            re.putParameter("orderId", orderId);
            request(re, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_load4supplier, onProductDetailRequestListener);
        }
    }

    private OnRequestListener<ProductAddEntity> onProductDetailRequestListener = new OnRequestListener<ProductAddEntity>() {
        @Override
        public ProductAddEntity jsonToObj(String responseStr) {
            System.out.println();
            return new Gson().fromJson(responseStr, ProductAddEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            showExceptionView(R.mipmap.icon_error, getString(R.string.net_error), HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            showExceptionView(R.mipmap.icon_error, arg + "", HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onStart(Object tag) {
            showProgressView();
        }

        @Override
        public void onResponse(ResponseEntity<ProductAddEntity> response, Object tag) {
            showMainView();
            ProductAddEntity responseElement = response.getResponseElement();
            productAddEntity = responseElement;
            if (productAddEntity == null) return;
            productAddEntity.setTopCategoryId(responseElement.getProductParseDto().getCategoryiId() + "");
            productAddEntity.setCategoryId(responseElement.getProductParseDto().getCategoryiiId() + "");
            productAddEntity.setNameId(responseElement.getProductParseDto().getCategoryiiiId() + "");
            productAddEntity.setMoq(responseElement.getProductSpecPrice().getMoq());
            productAddEntity.setType(responseElement.getProductParseDto().getType() + "");
            if (productAddEntity.getImages() != null && productAddEntity.getImages().size() > 0) {
                for (Images images : productAddEntity.getImages()) {
                    images.setAttachmentId(images.getImgId());
                }
            }
            productAddEntity.init();
            initProduct();
            saveUnit = productAddEntity.getChargeUnit();
        }
    };


    private void delete(final String productId) {

        CustomDialog.Builder builder = new CustomDialog.Builder(this);

        String s = "是否删除";
        if (!hasProductId() || listType == 3) {
            s = "是否放弃";
        }

        builder.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        dialog.dismiss();
                        if (listType == 3) {
                            finish();
                            return;
                        }
                        if (productId != null && !"".equals(productId)) {
                            List<String> ids = new ArrayList<>();
                            ids.add(productId);
                            requestProductDelete(ids);
                        } else {
                            intoProductList();
                            finish();
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builder.create().show();


    }


    private void requestProductDelete(List<String> ids) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_delete);
        RequestEntityMapSupply.putParameter("ids", ids);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_delete, onProductDeleteRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductDeleteRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                T.toast("删除成功");
                setResult(RESULT_OK);
                finish();
            } else {
                T.toast("删除失败");
            }

        }
    };

    private void help() {
        Intent intent = new Intent(this, WebActivity.class);
        StoreInfo storeInfo = getStoreInfo();
        if (storeInfo != null && storeInfo.isDc()) {
            intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_PRODUCT_DC);
        } else {
            intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_PRODUCT);

        }
        intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
        startActivity(intent);
    }

    RequestTag requestTag;

    private void requestTagList(boolean isSlice, final boolean isPack) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_tag_list);
        //1：商品标签；2：店铺标签
        RequestEntityMapSupply.putParameter("type", "1");
        //1散货,0整货
        if (getStoreInfo() != null && getStoreInfo().isDc()) {
            RequestEntityMapSupply.putParameter("isDc", "1");
        } else {
            RequestEntityMapSupply.putParameter("isDc", "0");
        }

        if (requestTag == null) {
            requestTag = new RequestTag();
            requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_tag_list;
        }
        if (isSlice)
            requestTag.type = RequestTag.TYPE_CURRENT;
        requestTag.action = isPack ? 1 : 0;
        request(RequestEntityMapSupply, requestTag, onTagListRequestListener);

    }

    private TagPackage tagPackage;
    private OnRequestListener<TagPackage> onTagListRequestListener = new OnRequestListener<TagPackage>() {
        @Override
        public TagPackage jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, TagPackage.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            if (tag instanceof RequestTag) {
                RequestTag requestTag = (RequestTag) tag;
                if (requestTag.type != RequestTag.TYPE_CURRENT) {
                    showProgressDialog();
                }
            }
        }

        @Override
        public void onResponse(ResponseEntity<TagPackage> response, Object tag) {
            hideProgressDialog();
            TagPackage responseElement = response.getResponseElement();
            if (responseElement != null) {
                tagPackage = responseElement;
                if (tag instanceof RequestTag) {
                    RequestTag requestTag = (RequestTag) tag;
                    if (requestTag.action == 1) {
                        intoPackage();
                    } else if (requestTag.type != RequestTag.TYPE_CURRENT) {
                        intoTag();
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel(requestTag);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (isNeedRefresh) {
            Intent intent = new Intent(this, ProductActivity.class);
            startActivity(intent);
            finish();
        } else {
            DataManager.getInstance().setProductAddEntity(null);
            Intent intent = new Intent();
            intent.putExtra("isClear", true);
            intent.putExtra("is_reset_category", false);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    protected void onToolbarBack() {
        onBackPressed();
    }

    @Override
    public void finish() {
        super.finish();
    }


    private List<String> priceUnitDraft = new ArrayList<>();

    private String getProductPriceUint(String data1, String data2) {

        priceUnitDraft.clear();

        if ("散货".equals(data2)) {

            if ("公斤".equals(data1) || "千克".equals(data1) || "斤".equals(data1) || "吨".equals(data1) || "克".equals(data1)) {
                priceUnitDraft.add(data1);
            } else {


                priceUnitDraft.add(data1);
                if (!isDc()) {
                    priceUnitDraft.add("公斤");
                } else {
                    //散货,非重量单位,重量可以输入小数
//                    edWeight.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
                }

            }

        } else {

            if ("公斤".equals(data1) || "千克".equals(data1) || "斤".equals(data1) || "吨".equals(data1) || "克".equals(data1)) {
                priceUnitDraft.add(data2);
                priceUnitDraft.add(data1);
            } else {
                priceUnitDraft.add(data1);
                priceUnitDraft.add(data2);
                priceUnitDraft.add("公斤");
            }

        }

        if (priceUnitDraft != null) {
            return new Gson().toJson(priceUnitDraft);
        }

        return "";

    }
}